package com.dapeng.cleardatabackend.interceptor.aop;

import com.dapeng.cleardatabackend.annotation.LogRunTime;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.stereotype.Component;

import java.util.concurrent.TimeUnit;

/**
 * @author dapeng
 * @description 记录方法执行时间
 */
@Aspect
@Component
@Slf4j
public class LogRunTimeInterceptor {

    @Around("@annotation(logRunTime)")
    public Object logExecutionTime(ProceedingJoinPoint joinPoint, LogRunTime logRunTime) throws Throwable {
        long start = System.currentTimeMillis();
        Object result;
        try {
            result = joinPoint.proceed();
        } catch (Exception e) {
            log.error("Method {} threw an exception: {}", joinPoint.getSignature(), e.getMessage());
            throw e;
        } finally {
            long end = System.currentTimeMillis();
            long duration = end - start;
            TimeUnit unit = logRunTime.value();
            long convertedDuration = TimeUnit.MILLISECONDS.convert(duration, unit);
            log.info("Method {} executed in {} {}", joinPoint.getSignature(), convertedDuration, unit.name().toLowerCase());
        }
        return result;
    }
}
